const util = require('util') //node 提供的
const axios = require('axios')
const { User } = require('../models/user')
const { generateToken } = require('../core/utils')
const WXBizDataCrypt = require('./WXBizDataCrypt')
class WXManager {
  static async codeToToken(code, encryptedData, iv) {
    //初始化登录的url
    const url = util.format(
      global.config.WX.url,
      global.config.WX.AppID,
      global.config.WX.AppSecret,
      code
    )
    //请求初始化之后的url
    //返回的errcode==0才会返回openid
    const result = await axios.get(url)
    if (result.status !== 200) {
      throw new global.errs.AuthFailed('openid获取失败')
    }
    if (result.data.errcode) {
      throw new global.errs.AuthFailed('openid获取失败:' + result.data.errmsg)
    }
    const { session_key } = result.data
    //  获取解密数据
    const pc = await new WXBizDataCrypt(global.config.WX.AppID, session_key)
    let userInfo = await pc.decryptData(encryptedData, iv)
    //从数据库查询是否存在openid
    let user = await User.getUserByUserOpenId(result.data.openid)
    if (!user) {
      user = await User.registerByUserOpenId(result.data.openid, userInfo)

    }
    return {
      token: generateToken(user.id, 2),
      userInfo: user.dataValues
    }
  }
}
module.exports = {
  WXManager,
}
